package com.amumu.drama.common.modules.captcha.service.impl;

import cn.hutool.json.JSONUtil;
import com.amumu.drama.common.base.annonation.Idempotent;
import com.amumu.drama.common.modules.captcha.service.CaptchaService;
import com.amumu.drama.common.modules.service.RedisService;
import com.amumu.drama.common.modules.service.ShortMessageService;
import com.amumu.drama.common.modules.service.impl.sms.model.SmsResponse;
import com.amumu.drama.common.utils.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    protected final Logger logger = LoggerFactory.getLogger(CaptchaServiceImpl.class);

    private final static String SMS_CODE_PREFIX = "login_captcha_%s";
    private final static long SMS_CODE_EXPIRE = 5 * 60L;

    @Autowired
    private RedisService redisService;
    @Autowired
    private ShortMessageService shortMessageService;

    @Override
    @Idempotent(key = "#phoneNum", expireTime = 10)
    public SmsResponse sendSmsCaptcha(String phoneNum) {

        String captcha = String.valueOf(ValidateUtils.generateCaptcha(6));
        SmsResponse smsResponse = this.doSendSmsCaptcha(phoneNum, captcha);
        if (smsResponse.getResult()) {
            redisService.set(String.format(SMS_CODE_PREFIX, phoneNum), captcha, SMS_CODE_EXPIRE);
        }
        return smsResponse;
    }

    @Override
    public boolean checkSmsCaptcha(String phoneNum, String captcha) {
        try {
            String redisCaptcha = (String) redisService.get(String.format(SMS_CODE_PREFIX, phoneNum));
            return Objects.equals(redisCaptcha, captcha);
        } catch (Exception e) {
            logger.error("checkSmsCaptcha {}-{} error: {}", phoneNum, captcha, e.getMessage(), e);
            return false;
        }
    }

    private SmsResponse doSendSmsCaptcha(String phoneNum, String captcha) {
        Map<String, String> params = new HashMap<>();
        params.put("captcha", captcha);
        return shortMessageService.sendSmsCaptcha(phoneNum, JSONUtil.toJsonStr(params));
    }
}
